//
// Created by 29108 on 2025/6/30.
//
#include "common/network/channel.h"
#include "common/logger/logger.h"
#include "common/network/event_loop.h"
#include <sys/epoll.h>
#include <cassert>

namespace common {
    namespace network {

        const int Channel::kNoneEvent = 0;
        const int Channel::kReadEvent = EPOLLIN | EPOLLPRI;
        const int Channel::kWriteEvent = EPOLLOUT;


        Channel::Channel(EventLoop *loop, int fd)
            : loop_(loop),
            fd_(fd),
            events_(0),
            revents_(0),
            index_(-1),
            eventHandling_(false),
            addedToLoop_(false){
        }

        Channel::~Channel() {
            try {
                // 1. 检查是否在事件处理中析构（这是危险的）
                if (eventHandling_) {
                    // 避免在析构时使用日志系统，使用标准错误输出
                    std::cerr << "[Channel] WARNING: Channel destroyed during event handling fd = " << fd_ << std::endl;
                    std::cerr << "[Channel] This may cause segmentation fault. Consider delayed destruction." << std::endl;
                    // 不要return，继续清理以避免资源泄露
                }

                // 2. 确保从事件循环中移除
                if (addedToLoop_ && loop_) {
                    if (loop_->isInLoopThread()) {
                        // 二次确认是否已移除
                        if (loop_->hasChannel(this)) {
                            loop_->removeChannel(this);
                        }
                    } else {
                        // 跨线程操作在析构时可能不安全，跳过
                        std::cerr << "[Channel] Skipping cross-thread removal in destructor for fd = " << fd_ << std::endl;
                    }
                    addedToLoop_ = false;
                }

                // 3. 标记析构状态（避免事件循环访问）
                // destructing_.store(true);

            } catch (const std::exception& e) {
                std::cerr << "[Channel] Exception in destructor for fd " << fd_ << ": " << e.what() << std::endl;
            } catch (...) {
                std::cerr << "[Channel] Unknown exception in destructor for fd " << fd_ << std::endl;
            }
        }

        void Channel::setThreadPool(std::shared_ptr<common::thread_pool::ThreadPool> pool) {
            thread_pool_ = pool;
            LOG_DEBUG("ThreadPool attached to Channel fd: " + std::to_string(fd_));
        }

        void Channel::handleEvent() {
            eventHandling_ = true;

            LOG_DEBUG("Channel::handleEvent fd = " + std::to_string(fd_) + " revents = " +  std::to_string(revents_));

            // 处理挂起事件（对端关闭连接）
            if ((revents_ & EPOLLHUP) && !(revents_ & EPOLLIN)) {
                if (closeCallback_) {
                    closeCallback_();
                }
            }

            // 处理错误事件
            if (revents_ & EPOLLERR) {
                if (errorCallback_) {
                    errorCallback_();
                }
            }

            // 处理可读事件
            if (revents_ & (EPOLLIN | EPOLLPRI | EPOLLRDHUP)) {
                if (readCallback_) {
                    readCallback_();
                } else {
                    LOG_WARNING("Channel::handleEvent - 读事件触发但没有回调函数 fd: " + std::to_string(fd_));
                }
            }

            // 处理可写事件
            if (revents_ & EPOLLOUT) {
                if (writeCallback_) {
                    // LOG_INFO("写事件 ");
                    writeCallback_();
                }
            }

            eventHandling_ = false;
        }

        void Channel::update() {
            addedToLoop_ = true;
            loop_->updateChannel(this);
        }

        void Channel::handleEventAsync() {
            if (thread_pool_) {
                // 使用线程池异步处理事件
                thread_pool_->submit([this]() {
                    try {
                        handleEvent();
                    } catch (const std::exception& e) {
                        LOG_ERROR("Async event handling failed for fd " + std::to_string(fd_) +
                                 ": " + std::string(e.what()));
                    } catch (...) {
                        LOG_ERROR("Async event handling failed for fd " + std::to_string(fd_) +
                                 " with unknown exception");
                    }
                });
            } else {
                // 同步处理事件
                handleEvent();
            }
        }

        void Channel::remove() {
            // 在移除前确保所有事件都被禁用
            if (!isNoneEvent()) {
                LOG_WARNING("Channel::remove() called with active events. fd=" + std::to_string(fd_) +
                           ", events=" + std::to_string(events_) + ". Auto-disabling...");

                // 强制禁用所有事件
                events_ = kNoneEvent;

                // 立即更新到epoll，确保事件被清除
                if (addedToLoop_ && loop_) {
                    try {
                        update();
                        LOG_DEBUG("Events force-disabled for fd=" + std::to_string(fd_));
                    } catch (const std::exception& e) {
                        LOG_ERROR("Failed to update events during force-disable: " + std::string(e.what()));
                    }
                }
            }

            addedToLoop_ = false;

            // 确保在EventLoop线程中执行removeChannel
            if (loop_->isInLoopThread()) {
                loop_->removeChannel(this);
            } else {
                // 跨线程安全移除
                loop_->runInLoop([this]() {
                    loop_->removeChannel(this);
                });
            }
        }
    }
}